import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../../core/constants.dart';
import '../../shared/models/daily_quiz.dart';

class QuizDetailPage extends ConsumerWidget {
  final DailyQuiz quiz;

  const QuizDetailPage({
    super.key,
    required this.quiz,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FA),
      appBar: AppBar(
        title: const Text('Quiz Details'),
        centerTitle: true,
        elevation: 0,
        backgroundColor: Colors.transparent,
        foregroundColor: AppConstants.DARK_BLUE,
        leading: Container(
          margin: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: AppConstants.PRIMARY_BLUE.withOpacity(0.1),
            borderRadius: BorderRadius.circular(12),
          ),
          child: IconButton(
            icon: const FaIcon(
              FontAwesomeIcons.arrowLeft,
              color: AppConstants.PRIMARY_BLUE,
              size: 18,
            ),
            onPressed: () => Navigator.pop(context),
          ),
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(24),
          child: Column(
            children: [
              _buildQuizHeader(),
              const SizedBox(height: 24),
              _buildQuizStats(),
              const SizedBox(height: 24),
              _buildPerformanceAnalysis(),
              const SizedBox(height: 24),
              _buildTimeInfo(),
              const SizedBox(height: 32),
              _buildActionButton(context),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildQuizHeader() {
    final accuracy = (quiz.accuracy * 100).toInt();
    final date = quiz.date;
    final dateStr = '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
    
    Color headerColor;
    IconData headerIcon;
    String headerTitle;
    
    if (accuracy >= 90) {
      headerColor = Colors.amber;
      headerIcon = FontAwesomeIcons.trophy;
      headerTitle = 'Excellent Performance!';
    } else if (accuracy >= 80) {
      headerColor = Colors.green;
      headerIcon = FontAwesomeIcons.medal;
      headerTitle = 'Great Job!';
    } else if (accuracy >= 70) {
      headerColor = Colors.blue;
      headerIcon = FontAwesomeIcons.thumbsUp;
      headerTitle = 'Good Work!';
    } else if (accuracy >= 60) {
      headerColor = Colors.orange;
      headerIcon = FontAwesomeIcons.handPeace;
      headerTitle = 'Keep Practicing!';
    } else {
      headerColor = Colors.red;
      headerIcon = FontAwesomeIcons.heart;
      headerTitle = 'Don\'t Give Up!';
    }

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            headerColor.withOpacity(0.1),
            headerColor.withOpacity(0.05),
          ],
        ),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(
          color: headerColor.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          Container(
            width: 80,
            height: 80,
            decoration: BoxDecoration(
              color: headerColor,
              shape: BoxShape.circle,
              boxShadow: [
                BoxShadow(
                  color: headerColor.withOpacity(0.3),
                  blurRadius: 15,
                  offset: const Offset(0, 8),
                ),
              ],
            ),
            child: Center(
              child: FaIcon(
                headerIcon,
                color: Colors.white,
                size: 32,
              ),
            ),
          ),
          const SizedBox(height: 16),
          Text(
            headerTitle,
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: headerColor,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            dateStr,
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            'Daily Quiz #${quiz.id.split('_').last}',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildQuizStats() {
    final accuracy = (quiz.accuracy * 100).toInt();
    final wrongAnswers = quiz.totalQuestions - quiz.correctAnswers;

    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: AppConstants.PRIMARY_BLUE.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const FaIcon(
                  FontAwesomeIcons.chartBar,
                  color: AppConstants.PRIMARY_BLUE,
                  size: 16,
                ),
              ),
              const SizedBox(width: 12),
              const Text(
                'Quiz Statistics',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: AppConstants.DARK_BLUE,
                ),
              ),
            ],
          ),
          const SizedBox(height: 20),
          Row(
            children: [
              Expanded(
                child: _buildStatItem(
                  'Total Questions',
                  '${quiz.totalQuestions}',
                  FontAwesomeIcons.listCheck,
                  Colors.blue,
                ),
              ),
              Expanded(
                child: _buildStatItem(
                  'Correct Answers',
                  '${quiz.correctAnswers}',
                  FontAwesomeIcons.circleCheck,
                  Colors.green,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: _buildStatItem(
                  'Wrong Answers',
                  '$wrongAnswers',
                  FontAwesomeIcons.xmark,
                  Colors.red,
                ),
              ),
              Expanded(
                child: _buildStatItem(
                  'Accuracy Rate',
                  '$accuracy%',
                  FontAwesomeIcons.bullseye,
                  Colors.orange,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(16),
      margin: const EdgeInsets.symmetric(horizontal: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.05),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: color.withOpacity(0.2),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          FaIcon(icon, color: color, size: 20),
          const SizedBox(height: 8),
          Text(
            value,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildPerformanceAnalysis() {
    final accuracy = (quiz.accuracy * 100).toInt();
    final wrongAnswers = quiz.totalQuestions - quiz.correctAnswers;
    
    String analysisText;
    Color analysisColor;
    IconData analysisIcon;
    List<String> tips = [];
    
    if (accuracy >= 90) {
      analysisText = 'Outstanding performance! You have excellent mastery of Esperanto vocabulary.';
      analysisColor = Colors.amber;
      analysisIcon = FontAwesomeIcons.star;
      tips = [
        'Keep up this excellent learning pace',
        'Try more challenging exercises',
        'Consider learning advanced grammar',
      ];
    } else if (accuracy >= 80) {
      analysisText = 'Great score! Your Esperanto learning is progressing well.';
      analysisColor = Colors.green;
      analysisIcon = FontAwesomeIcons.thumbsUp;
      tips = [
        'Continue reinforcing learned vocabulary',
        'Review incorrect questions carefully',
        'Maintain your daily practice habit',
      ];
    } else if (accuracy >= 70) {
      analysisText = 'Good performance! There\'s room for improvement.';
      analysisColor = Colors.blue;
      analysisIcon = FontAwesomeIcons.lightbulb;
      tips = [
        'Focus on reviewing incorrect vocabulary',
        'Increase daily study time',
        'Practice more vocabulary exercises',
      ];
    } else if (accuracy >= 60) {
      analysisText = 'Need more practice, but don\'t get discouraged!';
      analysisColor = Colors.orange;
      analysisIcon = FontAwesomeIcons.dumbbell;
      tips = [
        'Systematically review basic vocabulary',
        'Create a structured learning plan',
        'Use more memory techniques',
      ];
    } else {
      analysisText = 'Keep trying! Every practice session is progress.';
      analysisColor = Colors.red;
      analysisIcon = FontAwesomeIcons.heart;
      tips = [
        'Start with basic vocabulary',
        'Slow down your learning pace',
        'Find a study partner for help',
      ];
    }

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: analysisColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: FaIcon(
                  analysisIcon,
                  color: analysisColor,
                  size: 16,
                ),
              ),
              const SizedBox(width: 12),
              const Text(
                'Performance Analysis',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: AppConstants.DARK_BLUE,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Text(
            analysisText,
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[700],
              height: 1.5,
            ),
          ),
          if (wrongAnswers > 0) ...[
            const SizedBox(height: 12),
            Text(
              'You got $wrongAnswers questions wrong in this quiz. We recommend focusing on reviewing these vocabulary items.',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[600],
                fontStyle: FontStyle.italic,
              ),
            ),
          ],
          const SizedBox(height: 16),
          const Text(
            'Learning Tips:',
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.bold,
              color: AppConstants.DARK_BLUE,
            ),
          ),
          const SizedBox(height: 8),
                     ...tips.map((tip) => Padding(
             padding: const EdgeInsets.symmetric(vertical: 2),
             child: Row(
               crossAxisAlignment: CrossAxisAlignment.start,
               children: [
                 Container(
                   margin: const EdgeInsets.only(top: 6),
                   width: 4,
                   height: 4,
                   decoration: BoxDecoration(
                     color: analysisColor,
                     shape: BoxShape.circle,
                   ),
                 ),
                 const SizedBox(width: 8),
                 Expanded(
                   child: Text(
                     tip,
                     style: TextStyle(
                       fontSize: 14,
                       color: Colors.grey[600],
                     ),
                   ),
                 ),
               ],
             ),
           )),
        ],
      ),
    );
  }

  Widget _buildTimeInfo() {
    final duration = quiz.duration;
    final completedAt = quiz.completedAt;
    final speed = quiz.totalQuestions / (duration.inSeconds / 60);
    
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.purple.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const FaIcon(
                  FontAwesomeIcons.clock,
                  color: Colors.purple,
                  size: 16,
                ),
              ),
              const SizedBox(width: 12),
              const Text(
                'Time Information',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: AppConstants.DARK_BLUE,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: _buildTimeItem(
                  'Duration',
                  '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}',
                  FontAwesomeIcons.stopwatch,
                  Colors.blue,
                ),
              ),
              Expanded(
                child: _buildTimeItem(
                  'Speed',
                  '${speed.toStringAsFixed(1)}/min',
                  FontAwesomeIcons.gaugeHigh,
                  Colors.green,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Colors.grey.shade50,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              children: [
                const FaIcon(
                  FontAwesomeIcons.calendarCheck,
                  color: Colors.grey,
                  size: 14,
                ),
                const SizedBox(width: 8),
                Text(
                  'Completed at: ${completedAt.year}-${completedAt.month.toString().padLeft(2, '0')}-${completedAt.day.toString().padLeft(2, '0')} ${completedAt.hour.toString().padLeft(2, '0')}:${completedAt.minute.toString().padLeft(2, '0')}',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTimeItem(String label, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(12),
      margin: const EdgeInsets.symmetric(horizontal: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.05),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          FaIcon(icon, color: color, size: 16),
          const SizedBox(height: 6),
          Text(
            value,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          const SizedBox(height: 2),
          Text(
            label,
            style: TextStyle(
              fontSize: 11,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildActionButton(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      child: ElevatedButton.icon(
        onPressed: () => Navigator.pop(context),
        icon: const FaIcon(FontAwesomeIcons.arrowLeft, size: 16),
        label: const Text(
          'Back to Profile',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
          ),
        ),
        style: ElevatedButton.styleFrom(
          backgroundColor: AppConstants.PRIMARY_BLUE,
          foregroundColor: Colors.white,
          padding: const EdgeInsets.symmetric(vertical: 16),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          elevation: 2,
        ),
      ),
    );
  }
} 